package com.google.code.jholidays.events;

import com.google.code.jholidays.core.EventDescriptor;
import com.google.code.jholidays.events.parameters.Offset;
import com.google.code.jholidays.events.properties.DependentEventProperties;
import com.google.code.jholidays.parsers.OffsetParser;

/**
 * Implements {@link AbstractFactory} for creating {@link DependentEvent}
 * instances
 * 
 * @author tillias
 * 
 */
public class DependentEventFactory extends AbstractFactory {

    /**
     * Creates new instance of factory
     */
    public DependentEventFactory() {
	parser = new OffsetParser();
    }

    /**
     * {@inheritDoc}
     * <p>
     * This implementation depends on both parameters passed to this method.
     * Both of them mustn't be null otherwise method returns null.
     * <p>
     * If descriptor's expression field is valid for building {@link Offset}
     * instance and descriptor's parentID field is equal to parent event's id
     * returns new {@link DependentEvent} instance. Otherwise returns null
     */
    @Override
    protected AbstractEvent analizeExpression(EventDescriptor descriptor,
	    IEvent parent) {
	DependentEvent result = null;

	if (descriptor != null && parent != null) {
	    Offset offset = parser.parseOffset(descriptor.getExpression());

	    boolean idIsOk = parent.getID() == descriptor.getParentID();

	    if (offset != null && idIsOk) {
		DependentEventProperties properties = new DependentEventProperties(
			descriptor, parent, offset);
		result = new DependentEvent(properties);
	    }
	}

	return result;
    }

    /**
     * {@inheritDoc}
     * <p>
     * This implementation checks whether descriptor passed to this method isn't
     * null. If descriptor is not null and descriptor's expression field is
     * valid for building {@link Offset} instance returns true.
     * <p>
     * If descriptor parameter passed to this method is null or expressiong
     * field of descriptor can't be used to create {@link Offset} return false
     */
    @Override
    public boolean matches(EventDescriptor descriptor) {
	boolean result = false;

	if (descriptor != null)
	    result = parser.matches(descriptor.getExpression());

	return result;
    }

    OffsetParser parser;
}
